﻿Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Text.RegularExpressions

Public Class CnL_xup

    Public Function DownloadFile(ByVal _link As String) As String

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _post As String = String.Empty
        Dim _web_request_url As String = String.Empty
        Dim _byte_array() As Byte
        Dim _dataStream As Stream
        Dim _saveTo As String = String.Empty
        Dim _rt As String = String.Empty
        Dim _tmp_response As String = String.Empty

        Dim _vid As String = String.Empty
        Dim _vtime As String = String.Empty
        Dim _fid As String = String.Empty
        Dim _filename As String = String.Empty

        Try


            Debug.WriteLine("RAW Link:" & _link)

            'FID ermitteln

            _fid = _link.Remove(0, _link.IndexOf(","))
            _fid = _fid.Remove(_fid.IndexOf("/"))
            _fid = _fid.Remove(0, 1)
            _fid = _fid.Trim

            Debug.WriteLine("FID=" & _fid)

            'Dateiname ermitteln

            _filename = _link.Remove(_link.Length - 1)
            _filename = _filename.Remove(0, _filename.LastIndexOf("/"))
            _filename = _filename.Remove(0, 1)
            _filename = _filename.Trim

            Debug.WriteLine("Filename=" & _filename)

            'Web Request URL zusammenbauen

            _web_request_url = String.Format("http://www0.xup.in/exec/xddl.php?fid={0}&fname={1}&uid=0&key=", _fid, _filename)

            Debug.WriteLine("Web Request URL=" & _web_request_url)

            _http_webrequest = CType(HttpWebRequest.Create(_web_request_url), HttpWebRequest)

            _tmp_response = GetResponse(_link)

            _vid = GetvID(_tmp_response)
            _vtime = GetvTime(_tmp_response)

            Debug.WriteLine("VID=" & _vid)
            Debug.WriteLine("vTIME=" & _vtime)

            _post = String.Format("vid={0}&vtime={1}", _vid, _vtime)

            _byte_array = Encoding.Default.GetBytes(_post)

            With _http_webrequest

                .Method = "POST"
                .CookieContainer = _cookie_container
                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0"
                .ContentType = "application/x-www-form-urlencoded"
                .ContentLength = _byte_array.Length

            End With

            _dataStream = _http_webrequest.GetRequestStream()
            _dataStream.Write(_byte_array, 0, _byte_array.Length)

            _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

            _saveTo = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, IO.Path.GetRandomFileName)

            Dim writeStream As New FileStream(_saveTo, FileMode.Create, FileAccess.Write)

            ' write to the stream
            ReadWriteStream(_http_response.GetResponseStream(), writeStream)

            _http_response.Close()


        Catch ex As Exception
            _rt = ""
        End Try

        _rt = _saveTo

        Return _rt

    End Function


    Private Function GetResponse(ByVal url As String) As String

        Dim _cookie_container As New CookieContainer
        Dim _http_webrequest As HttpWebRequest
        Dim _http_response As HttpWebResponse
        Dim _rt As String

        _http_webrequest = CType(HttpWebRequest.Create(url), HttpWebRequest)
        _http_webrequest.CookieContainer = _cookie_container
        _http_response = CType(_http_webrequest.GetResponse(), HttpWebResponse)

        _rt = New StreamReader(_http_response.GetResponseStream()).ReadToEnd()

        _http_response.Close()

        Return _rt

    End Function

    Private Function GetvID(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("[a-z0-9]{34}")
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt

    End Function

    Private Function GetvTime(ByVal _web_response As String) As String

        Dim _rt As String = ""
        Dim sourcestring As String = _web_response
        Dim re As Regex = New Regex("[0-9]{10}" & Chr(34))
        Dim mc As MatchCollection = re.Matches(sourcestring)
        Dim mIdx As Integer = 0

        For Each m As Match In mc
            For groupIdx As Integer = 0 To m.Groups.Count - 1
                If Not String.IsNullOrEmpty(m.Value.ToString) Then
                    _rt = m.Value.ToString.Replace(Chr(34), "")
                End If
            Next
            mIdx = mIdx + 1
        Next

        Return _rt

    End Function

    Private Sub ReadWriteStream(readStream As Stream, writeStream As Stream)
        Dim Length As Integer = 256
        Dim buffer As [Byte]() = New [Byte](Length - 1) {}
        Dim bytesRead As Integer = readStream.Read(buffer, 0, Length)
        ' write the required bytes
        While bytesRead > 0
            writeStream.Write(buffer, 0, bytesRead)
            bytesRead = readStream.Read(buffer, 0, Length)
        End While
        readStream.Close()
        writeStream.Close()

        readStream.Dispose()
        writeStream.Dispose()

    End Sub

End Class
